import {
	accessMaxNumber
} from './constants.js'

const db = uniCloud.database();
const collection1 = db.collection('ha_access_list');
const collection2 = db.collection('ha_access_record');
const collection_user = db.collection('ha_user_account');
const collection_group = db.collection('ha_group_list');

// 检查提交的信息
async function checkAccessSubmit(submit) {
	let {
		name,
		account_id,
		group_id
	} = submit;

	name = name.replace(/\s*/g,"");
	if (name.length < 2) {
		return {
			pass: false,
			msg: '请输入出入点名称！'
		}
	}

	if (!account_id) {
		return {
			pass: false,
			msg: '请重新登录！'
		}
	}

	if (!group_id) {
		return {
			pass: false,
			msg: '请先进入团体，再创建！'
		}
	}

	// 检查用户
	let user = await collection_user
		.doc(account_id)
		.get();

	if (user.data && user.affectedDocs === 1){
	} else {
		return {
			pass: false,
			msg: '请重新登录！'
		}
	}

	// 检查团体
	let res_group = await collection_group
		.doc(group_id)
		.get();

	if (res_group.data && res_group.affectedDocs === 1){
	} else {
		return {
			pass: false,
			msg: '请先进入团体，再创建！'
		}
	}

	// 重名检查
	let res1 = await collection1
		.where({
			group_id,
			name
		})
		.get();

	if (res1.data && res1.affectedDocs >= 1) {
		return {
			pass: false,
			msg: '请不要创建重名出入点！'
		}
	}

	return {
		pass: true
	}
}

async function updateAccessItem(access_id,access_info) {
	await collection1
		.doc(access_id)
		.update(access_info);
}

async function checkAccessNumber(group_id) {
	let res = await collection1
		.where({
			group_id
		})
		.get();

	if (res.data && res.affectedDocs >= accessMaxNumber) {
		return false
	}
	return true;
}

async function getAccessRecord(access_id,page,length,condition = {}) {
	const result = await collection2
		.where(
			Object.assign({
				access_id
			},condition)
		)
		.orderBy("create_time","desc")
		.skip(length * page)
		.limit(length)
		.get();

	const recordList = [];
	for (var i = 0; i < result.data.length; i++) {
		const {
			_id,
			access_state,
			create_time,
			model
		} = result.data[i];

		recordList.push({
			_id,
			access_state,
			create_time,
			model
		});
	}

	return recordList;
}

async function getOneRecord(record_id) {
	let res2 = await collection2
		.doc(record_id)
		.get();

	if (res2.data && res2.affectedDocs === 1) {
	} else {
		return false;
	}

	if (res2.data[0].hasOwnProperty('access_id') == false) {
		return false;
	}

	let res1 = await collection1
		.doc(res2.data[0].access_id)
		.get();

	if (res1.data && res1.affectedDocs === 1) {
	} else {
		return false;
	}

	return {
		schema: res1.data[0].content,
		model: res2.data[0].model
	}
}

async function checkAccessItem(access_id,condition) {
	let res1 = await collection1
		.where(
			Object.assign({
				_id: access_id
			},condition)
		)
		.get();

	if (res1.data && res1.affectedDocs >= 1) {
		return true;
	} else {
		return false;
	}
}

export default {
	checkAccessSubmit,
	updateAccessItem,
	checkAccessNumber,
	getAccessRecord,
	getOneRecord,
	checkAccessItem
}